package com.LeeCode;

/**
 * 统计满足 K 约束的子字符串数量 I
 */

public class Code3258 {
    public static void main(String[] args) {
        String s = "1010101";
        int k = 2;
        System.out.println(new Code3258().countKConstraintSubstrings(s, k));
    }

    public int countKConstraintSubstrings(String s, int k) {
        int ans = 0, left = 0, n = s.length();
        int count0 = 0, count1 = 0;
        char[] chars = s.toCharArray();
        for (int right = 0; right < n; right++) {
            if (chars[right] == '0') {
                count0++;
            } else {
                count1++;
            }
            while (count0 > k && count1 > k) {
                if (chars[left] == '0') {
                    count0--;
                } else {
                    count1--;
                }
                left++;
            }

            ans += right - left + 1;
        }
        return ans;
    }
}
